package jinyilw.tools.h2db;

import jinyilw.common.file.FileTools;
import org.h2.tools.Server;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;

public class H2dbTools
{
	public static final String h2Driver = "org.h2.Driver";
	private H2dbTools()
	{
	}

	public static Server startH2TcpServer(int port, String path, String user,
			String password)
	{
		Server server = null;
		try
		{
			server = Server.createTcpServer("-tcpAllowOthers", "-tcpPort",
					String.valueOf(port));
			server.start();
			//			Class.forName("org.h2.Driver");
			//			DriverManager.getConnection("jdbc:h2:" + path, user, password);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return server;
	}

	public static Connection getH2TcpServerConnection(int port, String path,
			String user, String password)
	{
		Connection connection = null;
		try
		{
			Server.createTcpServer("-tcpAllowOthers", "-tcpPort",
					String.valueOf(port)).start();
			Class.forName("org.h2.Driver");
			connection = DriverManager.getConnection("jdbc:h2:" + path, user,
					password);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		if (connection != null)
			System.out
					.println("jdbc:h2:tcp:" + path + " database is connected!");
		return connection;
	}

	public static Connection getConnection(String path, String user,
			String password)
	{
		Connection connection = null;
		try
		{
			Class.forName("org.h2.Driver");
			connection = DriverManager.getConnection("jdbc:h2:" + path, user,
					password);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return connection;
	}

	public static File getFile(String h2dbPath)
	{
		if (h2dbPath == null)
			return null;
		String path = h2dbPath;
		if (h2dbPath.startsWith("~/"))
			path = FileTools.getUserHomePath() + h2dbPath.substring(1);
		else if (h2dbPath.startsWith("./"))
			path = h2dbPath.substring(1);
		path += ".mv.db";
		return new File(path);
	}
}
